﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.AuditLogging.StorageService.Configuration;
using Microsoft.Win32;
using System.IO;

namespace PSE.AuditLogging.StorageService.Management
{
    public class ConfigurationManager
    {
        private System.Configuration.Configuration _configFile;
        private LogServiceConfigurationSection _masterConfigSection;

        public ConfigurationManager()
        {
            string exeFilePath = Convert.ToString(Registry.GetValue(@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\BM&FBOVESPA Audit Logging Storage Service", "ImagePath", string.Empty));

            exeFilePath = exeFilePath.Replace("\"", "");

            if (!File.Exists(exeFilePath))
                throw new Exception("Error retrieving the service configuration file.");

            _configFile = System.Configuration.ConfigurationManager.OpenExeConfiguration(@exeFilePath);

            _masterConfigSection = _configFile.GetSection(Constants.LOGSERVICE_SECTION_NAME) as LogServiceConfigurationSection;

            if (_masterConfigSection == null)
                throw new Exception("Error retrieving the logService configuration section.");
        }

        public void AddOrUpdateProduct(ProductConfigurationElement productConfiguration)
        {
            //caso nao exista, adicionar
            if (_masterConfigSection.Products[productConfiguration.ProductId] == null)
                _masterConfigSection.Products.Add(productConfiguration);
            else
                _masterConfigSection.Products[productConfiguration.ProductId] = productConfiguration;

            _configFile.Save();
        }

        public void RemoveProduct(string productId)
        {
            //caso nao exista, adicionar
            if (_masterConfigSection.Products[productId] != null)
            {
                _masterConfigSection.Products.Remove(productId);
                _configFile.Save();
            }
        }

        public ProductConfigurationElement GetProductConfiguration(string productId)
        {
            return _masterConfigSection.Products[productId];
        }

        public List<ProductConfigurationElement> GetProductsConfigurations()
        {
            List<ProductConfigurationElement> ret = new List<ProductConfigurationElement>();
            foreach (ProductConfigurationElement item in _masterConfigSection.Products)
            {
                ret.Add(item);
            }

            return ret;
        }

        public List<string> GetConfiguredProducts()
        {
            List<string> ret = new List<string>();
            foreach (ProductConfigurationElement item in _masterConfigSection.Products)
            {
                ret.Add(item.ProductId);
            }

            return ret;
        }
    }
}
